﻿using EndpointManagement;
using IM.Easy.Core.Cache;
using IM.Easy.SystemServices.IServices;
using IM.Easy.SystemServices.Services;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;

namespace IM.Easy.Api.HostedService
{

    /// <summary>
    /// 缓存加载器--->加载系统接口权限到缓存中
    /// </summary>
    public class ApiPermissionCacheLoader : IHostedService
    {
        private readonly ILogger<ApiPermissionCacheLoader> _logger;
        private readonly IApiPermissionsService apiPermissionsService;


        public ApiPermissionCacheLoader(
            ILogger<ApiPermissionCacheLoader> logger,
             IApiPermissionsService apiPermissionsService)
        {
            _logger = logger;
            this.apiPermissionsService = apiPermissionsService;
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {
            Console.WriteLine("正在启动API权限缓存加载器...");
            LoadApiPermissions();
            return Task.CompletedTask;
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            Console.WriteLine("正在停止API权限缓存加载器...");
            return Task.CompletedTask;
        }

        /// <summary>
        /// 加载 API 权限到内存缓存
        /// </summary>
        private void LoadApiPermissions()
        {
            var apiPermissions = apiPermissionsService.GetList();
            // 将数据加载到缓存
            apiPermissions.ForEach(permission =>
            {
                EndPointManager.Register($"{permission.Path}:{permission.HttpMethod}", permission);
            });

            Console.WriteLine("已加载 {0} 个API权限到缓存中。", apiPermissions.Count);
        }
    }
}
